package com.tuniu.activity;

import com.tuniu.R;
import com.tuniu.tabFragment.CustomerServiceFragment;
import com.tuniu.tabFragment.FoundFragment;
import com.tuniu.tabFragment.HomeFragment;
import com.tuniu.tabFragment.JourneyPlayFragment;
import com.tuniu.tabFragment.MineFragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends FragmentActivity {

	private FragmentTabHost mTabHost;
	private int imgtabs[] = { R.drawable.tab_icon_home, R.drawable.tab_icon_journey, R.drawable.tab_icon_found,
			R.drawable.tab_icon_service, R.drawable.tab_icon_mine };

	private int tvtabs[] = { R.string.main_tab_name_home, R.string.main_tab_name_journey, R.string.main_tab_name_found,
			R.string.main_tab_name_service, R.string.main_tab_name_mine, };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initTab();

	}
	
	private boolean isExit;
	private Handler mhandler =new Handler();
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (!isExit) {
				Toast.makeText(MainActivity.this, "再次点击退出途牛", Toast.LENGTH_SHORT).show();
				isExit=true;
				//两秒之内按下后直接执行  else语句，退出应用
				//两秒后按下，重置变量，进入if语句
				mhandler.postDelayed(new Runnable() {
					
					@Override
					public void run() {
						isExit=false;
					}
				}, 2000);
				//拦截事件
				return true;
			}else{
				finish();
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	private void initTab() {
		mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
		mTabHost.addTab(mTabHost.newTabSpec("HomeFragment").setIndicator(getIndicator(0)), HomeFragment.class, null);
		mTabHost.addTab(mTabHost.newTabSpec("JourneyPlayFragment").setIndicator(getIndicator(1)), JourneyPlayFragment.class, null);
		mTabHost.addTab(mTabHost.newTabSpec("FoundFragment").setIndicator(getIndicator(2)), FoundFragment.class, null);
		mTabHost.addTab(mTabHost.newTabSpec("CustomerServiceFragment").setIndicator(getIndicator(3)), CustomerServiceFragment.class,null);
		mTabHost.addTab(mTabHost.newTabSpec("MineFragment").setIndicator(getIndicator(4)), MineFragment.class, null);

	}

	private View getIndicator(int index) {
		View view = getLayoutInflater().inflate(R.layout.indicator_tabs, null);
		ImageView mImageView = (ImageView) view.findViewById(R.id.iv_tabs);
		TextView tabs_tv = (TextView) view.findViewById(R.id.tv_tabs);
		mImageView.setImageResource(imgtabs[index]);
		tabs_tv.setText(tvtabs[index]);
		return view;
	}

}
